using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace TestTD
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        BasicEffect basicEffect;

        Texture2D backgroundTexture;

        GameObject mouseCursor;
        GameObject[] towers;
        GameObject[] obstacles;

        // Will draw and move soon-ish
        GameObject[] enemies;

        // Need to calculate position of waypoints
        VertexPositionColor[] waypoints;
        const Boolean pathDebugDraw = true;

        int numTowers = 0;
        ButtonState prevLeftClickState = ButtonState.Released;
        Boolean isBuildMode = false;
        Boolean isCollision = false;

        const int MAX_NUM_TOWERS = 5;

        Rectangle viewportRect;

        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            basicEffect = new BasicEffect(spriteBatch.GraphicsDevice, null);
            basicEffect.VertexColorEnabled = true;

            //load background image
            backgroundTexture = Content.Load<Texture2D>("Sprites\\path");

            // Create the mouse cursor object
            mouseCursor = new GameObject(Content.Load<Texture2D>("Sprites\\cursor"));

            // Create Enemy Array
            enemies = new GameObject[5];
            for (int i = 0; i < 5; i++)
            {
                enemies[i] = new GameObject(Content.Load<Texture2D>("Sprites\\enemy"));
            }

            // Create the tower and obstacle objects
            towers = new GameObject[MAX_NUM_TOWERS];
            obstacles = new GameObject[2];
            for (int i = 0; i < MAX_NUM_TOWERS; i++)
            {
                towers[i] = new GameObject(Content.Load<Texture2D>("Sprites\\tower"));
            }
            for (int i = 0; i < 2; i++)
            {
                // Just use tower sprit for now, we can chage it later
                obstacles[i] = new GameObject(Content.Load<Texture2D>("Sprites\\tower"));
            }
            obstacles[0].position.X = 100;
            obstacles[0].position.Y = 200;
            obstacles[1].position.X = 600;
            obstacles[1].position.Y = 400;

            waypoints = new VertexPositionColor[6];
            waypoints[0].Position.X = 255;
            waypoints[0].Position.Y = 0;
            waypoints[0].Color = Color.Red;
            waypoints[1].Position.X = 240;
            waypoints[1].Position.Y = 165;
            waypoints[1].Color = Color.Red;
            waypoints[2].Position.X = 435;
            waypoints[2].Position.Y = 185;
            waypoints[2].Color = Color.Red;
            waypoints[3].Position.X = 435;
            waypoints[3].Position.Y = 460;
            waypoints[3].Color = Color.Red;
            waypoints[4].Position.X = 590;
            waypoints[4].Position.Y = 475;
            waypoints[4].Color = Color.Red;
            waypoints[5].Position.X = 590;
            waypoints[5].Position.Y = 600;
            waypoints[5].Color = Color.Red;

            viewportRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            Boolean isBuilding = false;
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            isCollision = false;

            MouseState mouseState = Mouse.GetState();

            isBuildMode = (mouseState.LeftButton == ButtonState.Pressed);
            if (mouseState.LeftButton == ButtonState.Released &&
                prevLeftClickState == ButtonState.Pressed)
            {
                isBuilding = true;
            }
            prevLeftClickState = mouseState.LeftButton;
            mouseCursor.position.X = mouseState.X;
            mouseCursor.position.Y = mouseState.Y;
            if (isBuilding || isBuildMode)
            {
                //Collision Detection
                foreach (GameObject obstacle in obstacles)
                {
                    if ((obstacle.position - mouseCursor.position).LengthSquared() <= (4 * obstacle.center.X * obstacle.center.X))
                    {
                        isCollision = true;
                        break;
                    }
                }
                foreach (GameObject tower in towers)
                {
                    if (tower.valid &&
                       (tower.position - mouseCursor.position).LengthSquared() <= (4 * tower.center.X * tower.center.X))
                    {
                        isCollision = true;
                        break;
                    }
                }
            }
            if (isBuilding && (!isCollision) && numTowers < MAX_NUM_TOWERS)
            {
                towers[numTowers].position = mouseCursor.position;
                towers[numTowers].valid = true;
                numTowers++;
            }

            foreach (GameObject tower in towers)
            {
                if (tower.valid)
                {
                    tower.rotation = (float) Math.Atan2((mouseCursor.position.Y - tower.position.Y), (mouseCursor.position.X - tower.position.X));
                }
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);

            spriteBatch.Draw(backgroundTexture, viewportRect, Color.White);

            foreach (GameObject obstacle in obstacles)
            {
                spriteBatch.Draw(obstacle.sprite, obstacle.position, null, Color.Olive, 0f, obstacle.center, 1.0f, SpriteEffects.None, 0F);
            }
            foreach (GameObject tower in towers)
            {
                if (tower.valid)
                {
                    spriteBatch.Draw(tower.sprite, tower.position, null, Color.White, tower.rotation, tower.center, 1.0f, SpriteEffects.None, 0F);
                }
            }

            if (isBuildMode)
            {
                if (isCollision || numTowers >= MAX_NUM_TOWERS)
                {
                    spriteBatch.Draw(towers[0].sprite, mouseCursor.position, null, Color.Red, 0f, towers[0].center, 1.0f, SpriteEffects.None, 0F);
                }
                else
                {
                    spriteBatch.Draw(towers[0].sprite, mouseCursor.position, null, Color.LightGreen, 0f, towers[0].center, 1.0f, SpriteEffects.None, 0F);
                }
            }

            //Code to draw cursor.
            spriteBatch.Draw(mouseCursor.sprite , mouseCursor.position, null, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0F);

            spriteBatch.End();

            if (pathDebugDraw)
            {
                basicEffect.Begin();
                spriteBatch.GraphicsDevice.VertexDeclaration = new VertexDeclaration(spriteBatch.GraphicsDevice, VertexPositionColor.VertexElements);
                spriteBatch.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineStrip, waypoints, 0, 5);
                basicEffect.End();
            }

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}
